const app = getApp();
const { module: moduleName, tabbar_type } = app.siteInfo;
const { getOpenID } = require('../../utils/ws/wsxcx-opendata-sdk');

// share时强制添加用户本人的uid。
function spliceSharePath(path, type) {
  let openid = '';

  if (moduleName === 'ws_micro_shop') {
    openid = wx.getStorageSync('OPENID');
    if (path.indexOf('?') === -1) {
      path += '?openidNew=' + openid + '&share_scene=3';
    } else {
      path += '&openidNew=' + openid + '&share_scene=3';
    }
    return path;
  } else if (moduleName === 'ws_diancan_multi') {
    openid = wx.getStorageSync('openid');
    if (!openid) {
      openid = wx.getStorageSync('userInfo') && wx.getStorageSync('userInfo').openid;
    }
    if (path.indexOf('?') === -1) {
      path += '?openidNew=' + openid + '&share_scene=3';
    } else {
      path += '&openidNew=' + openid + '&share_scene=3';
    }
    return path;
  } else {
    openid = wx.getStorageSync('userInfo') && wx.getStorageSync('userInfo').openid;
    if (path.indexOf('?') === -1) {
      path += '?openidNew=' + openid + '&share_scene=3';
    } else {
      path += '&openidNew=' + openid + '&share_scene=3';
    }
    return path;
  }
}

// 通用的uid与openid互查方法
function uidOrOpenid(param) {
  const uidExp = /^[0-9]*$/;
  return new Promise(function(resolve, reject) {
    app.util.request({
      url: 'card/api/get_fans',
      data: {
        uid: uidExp.test(param) ? param : '',
        openid: !uidExp.test(param) ? param : '',
      },
      success: function (res) {
        if (res.data.errno === 0) {
          resolve(res.data.data);
        }
      },
    });
  });
}

// 从app的options中解析参数。平台通用。
function parseQuery() {
  const appOptions = app.globalData && app.globalData.appOptions;
  const { scene, query } = appOptions;
  if (scene === 'share' || scene === 'QRCodeA') {
    return query;
  } else if (scene === 'QRCodeB') {
    let scenePair = decodeURIComponent(query.scene).split('&');
    let sceneObj = {};
    scenePair.forEach(function(item) {
      let key = item.slice(0, item.indexOf('='));
      let value = item.slice(item.indexOf('=') + 1, item.length);
      sceneObj[key] = value;
    });
    return sceneObj;
  }
}

// 向后端发送openid和fromOpenid
function sendBindInfo(_util) {
  let { openid } = wx.getStorageSync('OPENID') || wx.getStorageSync('openid');
  const query = _util.parseQuery();
  const fromUid = query && query.uid;
  let fromOpenid = query && query.openid;
  // 如果参数中有openid
  if (fromOpenid) {
    if (!openid) {
      if (moduleName === 'ws_micro_shop') {
        app.ws_micro_shoplogin().then(function () {
          openid = wx.getStorageSync('OPENID');
          if (fromOpenid && openid && fromOpenid !== openid) {
            app.util.request({
              url: 'card/api/bind_from',
              data: {
                openid,
                fromOpenid,
              },
            });
          }
        });
      } else {
        app.util._wxLogin().then(res => {
          openid = res.openid ? res.openid : res.data.data.openid;
          console.log(fromOpenid, openid);
          if (fromOpenid && openid && fromOpenid !== openid) {
            app.util.request({
              url: 'card/api/bind_from',
              data: {
                openid,
                fromOpenid,
              },
            });
          }
        });
      }
    } else {
      if (fromOpenid && openid && fromOpenid !== openid) {
        app.util.request({
          url: 'card/api/bind_from',
          data: {
            openid,
            fromOpenid,
          },
        });
      }
    }
  } else if (fromUid) {  // 如果没有openid，但是有uid。
    this.uidOrOpenid(fromUid).then(res => {
      fromOpenid = res.openid;
      if (!openid) {
        if (moduleName === 'ws_micro_shop') {
          app.ws_micro_shoplogin().then(function () {
            openid = wx.getStorageSync('OPENID');
            if (fromOpenid && openid && fromOpenid !== openid) {
              app.util.request({
                url: 'card/api/bind_from',
                data: {
                  openid,
                  fromOpenid,
                },
              });
            }
          });
        } else {
          app.util._wxLogin().then(res => {
            openid = res.openid ? res.openid : res.data.data.openid;
            console.log(fromOpenid, openid);
            if (fromOpenid && openid && fromOpenid !== openid) {
              app.util.request({
                url: 'card/api/bind_from',
                data: {
                  openid,
                  fromOpenid,
                },
              });
            }
          });
        }
      } else {
        if (fromOpenid && openid && fromOpenid !== openid) {
          app.util.request({
            url: 'card/api/bind_from',
            data: {
              openid,
              fromOpenid,
            },
          });
        }
      }
    });
  }
}

function loginBeforeGetMobile() {
  return new Promise((resolve, reject) => {
    wx.login({
      success: function (res) {
        if (res.code) {
          let code = res.code;
          const systemInfo = wx.getSystemInfoSync();
          if (moduleName === 'ws_micro_shop') {
            app.ws_micro_shoprequest({
              url: app.api.passport.login2,
              method: 'post',
              data: {
                code,
                brand: systemInfo.brand,
                model: systemInfo.model,
              },
              success: function (res) {
                if (Number(res.code) === 0) {
                  console.log('micro shop login2 under loginBeforeGetMobile success:', res.data);
                  let userInfo = wx.getStorageSync('userInfo') || {};
                  userInfo.sessionid = res.data.access_token;
                  userInfo.openid = res.data.openid;

                  wx.setStorageSync('access_token', res.data.access_token);
                  wx.setStorageSync('OPENID', res.data.openid);
                  wx.setStorageSync('userInfo', userInfo);

                  wx.setStorageSync('user_info', {
                    nickname: res.data.nickname,
                    avatar_url: res.data.avatar_url,
                    info: res.data.info,
                    is_distributor: res.data.is_distributor,
                    parent: res.data.parent,
                    id: res.data.id,
                    is_clerk: res.data.is_clerk,
                    auth_mode: res.data.auth_mode,
                    mobile: res.data.mobile,
                  });
                  resolve(res.data.openid);
                } else {
                  wx.showToast({
                    title: res.msg,
                  });
                  reject(new Error(false));
                }
              },
            });
          } else {
            app.util.request({
              url: 'auth/session/openid',
              data: {
                code,
                brand: systemInfo.brand,
                model: systemInfo.model,
              },
              cachetime: 0,
              success: (session) => {
                let userInfo = wx.getStorageSync('userInfo') || {};
                userInfo.sessionid = session.data.data.sessionid;
                userInfo.openid = session.data.data.openid;
                wx.setStorageSync('userInfo', userInfo);
                resolve(session.data.data.openid);
              },
              fail: (err) => {
                // TODO
                reject(err);
              },
            });
          }
        }
      },
    });
  });
}

function shouldShowFixedMenu(pageUrl) {
  let tabBars = [];
  let tabBarPages = [];
  let currentModuleIndex = app.tabbarindex;
  if (tabbar_type === '2') return true;

  if (app && app.tabInfo && app.tabInfo[currentModuleIndex] && app.tabInfo[currentModuleIndex].tabBar) {
    tabBars = app.tabInfo[currentModuleIndex].tabBar.list;
    tabBars.forEach(item => tabBarPages.push(item.pagePath));
  }
  if (tabBarPages.indexOf(pageUrl) !== -1) return false; // 仅当菜单为原生菜单 & 页面为菜单页面，则不显示自有虚拟菜单
  else return true;
}

function sendFormID(id) {
  if (wx.getStorageSync('wsOpenID')) {
    app.util.request({
      url: 'pushService/api/formid',
      data: { formid: id },
      method: 'post',
    });
  } else {
    getOpenID({ mode: 1 }).then(() => {
      app.util.request({
        url: 'pushService/api/formid',
        data: { formid: id },
        method: 'post',
      });
    });
  }
}

function checkUserTelephone(e) {
  let openid =  wx.getStorageSync('wsOpenID') || wx.getStorageSync('OPENID');
  return openid ? doCheckUserTel.call(this, openid, e) : getOpenID({ mode: 1 }).then(openid => {
    doCheckUserTel.call(this, openid, e);
  });
}

function doCheckUserTel(openid, e) {
  const that = this;
  app.util.request({
    url: 'card/api/is_up_user',
    data: {
      openid,
      type: 'is_phone',
    },
    success: function (res) {
      if (Number(res.data.data) === 0) {
        that.setData({
          showBindMobile: true,
        });
      } else if (Number(res.data.data) === 1) {
        that.setData({
          myBasicInfo: res.data.uinfo || {},
          myBasicCardInfo: res.data.card_info || {},
          guestMobile: res.data.uinfo.phone,
        }, () => {
          that.gotoMsg(e);
        });
      }
    },
  });
}

//获取订阅消息模版ID
function getSubscribeMessageTemplate() { 
  return new Promise((resolve, reject) => {
    app.util.request({
      url: 'card/submsg/getTmplConfig',
      showLoading: true,
      success: res => {
        if(res.data && res.data.errcode === 0) {
          const { subscribe_message_pritmpl_id: templateId = '' } = res.data.data;
          resolve(templateId);
        }else {
          reject(res);
        }
      },
      fail: res => {
        reject(res);
      }
    });
  })
}

//调起客户端小程序订阅消息界面
async function requestSubscribeMessage() {
  try {
    const templateId =  await this.getSubscribeMessageTemplate();
    if (!templateId) {
      wx.showToast({
        title: '模版ID获取失败',
        icon: 'none',
      });
      return;
    }
    return new Promise((resolve, reject) => {
      wx.requestSubscribeMessage({
        tmplIds: [templateId],
        success: (res) => {
          if (res[templateId] === 'accept') {
            app.util.request({
              url:'card/submsg/addNum',
              data:{
                openid: wx.getStorageSync('OPENID')
              },
              success: res => {
                console.log("======addNum=====",res);
              }
            });
            console.log('requestSubscribeMessage 订阅消息成功');
            resolve(res);
          } else {
            console.log('requestSubscribeMessage 订阅消息失败',res[templateId]);
            resolve(res);
          }
        },
        fail: (err) => {
          console.log('requestSubscribeMessage 订阅消息失败',JSON.stringify(err));
          reject(res);
        },
      })
    })
  } catch (error) {
    console.log('getSubscribeMessageTemplate 获取订阅消息模板Id 调用失败',error);
  }
}

module.exports = {
  spliceSharePath,
  uidOrOpenid,
  parseQuery,
  sendBindInfo,
  loginBeforeGetMobile,
  shouldShowFixedMenu,
  sendFormID,
  checkUserTelephone,
  getSubscribeMessageTemplate,
  requestSubscribeMessage,
  first_visit: true,
};
